function noCache(uri){return uri.concat(/\?/.test(uri)?"&":"?","noCache=",(new Date).getTime(),".",Math.random()*1234567)};



var tweetListJs = { 
			// call icon click 
		      makeCall : function(destination){
	      				$("#phoneDiv").css("display","block");
	      				dial(destination);
	      			},
			  // reply to~  	
			  replyTo : function(reply2Id,tweetID){
      				var message = "@"+reply2Id + " ";
//	      			var message = "@"+reply2Id;
//	      			var tag = document.getElementById("tag").value;
//	      			if(tag.length > 0) {
//	      				message += (" #" + tag + " ");
//	      			}
					document.getElementById("message").value = message;
					document.getElementById("tweetid").value= tweetID;
		        
				},
				// 글등록시 List Refresh
				// 기존 페이지 수와 동일하게 보기위해 1페이지 고정
			  updateList : function(){
					
					var this_url = location.href; 
					var tag = document.getElementById("tag").value; 
					var tagType = document.getElementById("tagType").value;
					var nowPage = document.getElementById("nowPage").value;
					var countPerPage = document.getElementById("countPerPage").value;
					// 출력하는 수를 계산  ex) 3페이지에서 글등록시 60개를 출력하기위해서 계산
					var printLine = parseInt(nowPage) * parseInt(countPerPage);
					var totalCount = document.getElementById("totalCount").value;
					if(this_url.indexOf("tweetList.do")>0) { 
						$.ajax({
						    url: noCache('/searchList4Ajax.do?tag='+ escape(encodeURIComponent(tag))
						    		+'&tagType='+tagType
						    		+'&nowPage='+1
							    	+'&countPerPage='+printLine),
						    timeout: 3000,
						    error: function(){
						        alert('Error loading List Page');
						    },
						    success: function(html){
						        $('#timeline').html(html);
						        
						        // message 초기화
						        clearInsertForm();
						        
						        document.getElementById("nowPage").value = nowPage;
						        
						        // more 버튼 숨김 여부
						        moreButtonDisplay();
						        
						    }
						});
					}else{
						document.location.href="/tweetList.do";
					}	
				},
				// 태그 검색, mention ID 로 검색시  
				// tweetRight에서 호출
				searchList : function(tag,tagType){
					var this_url = location.href;
					if(this_url.indexOf("tweetList.do")>0) { 
						var nowPage = 1;
						var countPerPage = document.getElementById("countPerPage").value;
						$.ajax({
						    url: '/searchList4Ajax.do?tag='+ escape(encodeURIComponent(tag))
					    		+'&tagType='+tagType
					    		+'&nowPage='+1
						    	+'&countPerPage='+countPerPage,
						    timeout: 3000,
						    type : 'POST',
						    error: function(){
						        alert('Error loading List Page');
						    },
						    success: function(html){
						        $('#timeline').html(html);
						        
						        document.getElementById("tag").value = tag; 
								document.getElementById("tagType").value = tagType;
								document.getElementById("nowPage").value = nowPage;
								
								// message 초기화
								clearInsertForm();
								
						        // more 버튼 숨김 여부
						        moreButtonDisplay();
						    }
						});	
					}else{
						document.location.href='/tweetList.do?tag='+ escape(encodeURIComponent(tag))+'&tagType='+tagType; 
					}
				},
				// 좀더 보기  
				moreList : function() {
					var this_url = location.href; 
					if(this_url.indexOf("tweetList.do")>0) { 
						var tag = document.getElementById("tag").value; 
						var tagType = document.getElementById("tagType").value;
						var nowPage = 1 + parseInt(document.getElementById("nowPage").value);
						var countPerPage = document.getElementById("countPerPage").value;
						$.ajax({
						    url: '/searchList4Ajax.do?tag='+ escape(encodeURIComponent(tag))
						    	+'&tagType='+tagType
						    	+'&nowPage='+nowPage
						    	+'&countPerPage='+countPerPage,
						    timeout: 3000,
						    type : 'POST',
						    error: function(){
						        alert('Error loading List Page');
						    },
						    success: function(html){
						        $('#timeline').append(html);
						        
						        document.getElementById("nowPage").value = nowPage;
						        // more 버튼 숨김 여부
						        moreButtonDisplay();
						    }
						});	
					}else{
						document.location.href='/tweetList.do?tag='+ escape(encodeURIComponent(tag))+'&tagType='+tagType; 
					}
				},
				// 글 삭제 
				deleteList : function(tweetID){ 

			         $.ajax({
			            url: '/tweetDelete.do?tweetid='+tweetID,
			            type: 'GET',
			            dataType: 'json',
			            timeout: 3000,
			            complete: function(res) { 
			                 var jsonData = eval("(" + res.responseText + ")");
			                 if(jsonData.errorCode == "1") {
			                	 tweetListJs.updateList();
			                	 finishMessageSet("Delete Tweet!");
			                 } else {
			                     alert('error : ' + jsonData.errorDesc);
			                     tweetListJs.updateList();
			                 }
			           }
			         });
				}	      
			
	}

// more 버튼 숨김 여부
function moreButtonDisplay() {
	 var totalCount = document.getElementById("totalCount").value;
     var listCount = document.getElementById("timeline").getElementsByTagName("li").length;
     if(totalCount <= listCount) {
     	document.getElementById("pagination").style.display = "none";
     } else {
     	document.getElementById("pagination").style.display = "block";
     }
}

//message input clear
function clearInsertForm() {
	document.getElementById("message").value = ""; 
    document.getElementById("sms").checked = false ;
    document.getElementById("message_cnt").innerHTML = document.getElementById("message").value.length;
    document.getElementById("tweetid").value= "";
}

// 글 등록 또는 글 삭제 후 message 출력
function finishMessageSet(message) {
	 $('#completedMessageDiv').html(message);
	 var fontSize = "1.2em";
	 var lineHeight = "1.1";
	 var color = "red";
	 $('#completedMessageDiv').css({'font-size':fontSize,'line-height':lineHeight,'color':color});
	setTimeout("finishMessageClear()", 2000);
}

function finishMessageClear() {
	$('#completedMessageDiv').html("");
}

// SMS 
$('a[name=modal]').click(function(e) {        
	//Cancel the link behavior        
	e.preventDefault();        
	//Get the A tag       
	 var id = $(this).attr('href');        
	//Get the screen height and width       
	 var maskHeight = $(document).height();        
	 var maskWidth = $(window).width();        
	 //Set heigth and width to mask to fill up the whole screen        
	 $('#mask').css({'width':maskWidth,'height':maskHeight});        
	 //transition effect                     
	 $('#mask').fadeIn(1000);                
	 $('#mask').fadeTo("slow",0.8);          
	 //Get the window height and width        
	 var winH = $(window).height();        
	 var winW = $(window).width();        
	 //Set the popup window to center        
	 $(id).css('top',  winH/2-$(id).height()/2);        
	 $(id).css('left', winW/2-$(id).width()/2);        
	 //transition effect        
	 $(id).fadeIn(2000);     

	 // call ajax  
	 getSMSPage();

	 });    
function getSMSPage(){ 
$.ajax({
    url: '/sms.do',
    timeout: 1000,
    error: function(){
        alert('Error loading SMS Page');
    },
    success: function(html){
        $('#dialog').append(html);
      // $('#mask').innerHTML = html;
        
    }
});
}


//if close button is clicked    
$('.window .close').click(function (e) {        
	//Cancel the link behavior        
	e.preventDefault();        
	$('#mask').hide();        
	$('.window').hide();  
	
});  

var tweetInsertJs = {
	     goInsert : function(){

		     var contents = document.getElementById("message").value;

		     if(contents.length < 1) {
	             alert("글을 등록하세요.");
	             return;
		     }
	         
	         var queryString = $("#tweetForm").serialize();
	         //alert(queryString);

	         var strUrl = "/tweetInsert.do";
	         //alert(strUrl);
	                  
	         $.ajax({
	             url: strUrl,
	             type: 'POST',
	             data: queryString,
	             dataType: 'json',
	             complete: function(res) { 
	                 // unblock when remote call returns 
	                 var jsonData = eval("(" + res.responseText + ")");
	                 if(jsonData.errorCode == "1") {
	                	 tweetListJs.updateList();
	                	 finishMessageSet("Insert Tweet!");
	                 } else {
	                	 alert('error : ' + jsonData.errorDesc);
	                     tweetListJs.updateList();
	                 }
	             } 
	         });
	    },  // call ajax     


	    checkWordCnt : function(){

	      var maxContentSize = 140;        
	      var contents = document.getElementById('message');
	      var wordCnt = document.getElementById('message_cnt');

	        
	        wordCnt.innerHTML = contents.value.length;
	        
	        if(contents.value.length > maxContentSize){
	          alert('OVER');
	          contents.value = contents.value.substring(0, maxContentSize);
	          wordCnt.innerHTML = contents.value.length;
	          return;
	        }
	      
	      return; 
	    }
	 }

	var tweetCallJs = { 
		  // 전화 발신 시 Log 저장 
		  updateCallLog : function(_source, _destination){
				$.ajax({
					url:  noCache('/insertCallLog.do?source=' + _source + '&destination=' + _destination),
				    timeout: 3000,
				    error: function(){
				        alert('Call Log Update Fail!!');
				    },
				    success: function(html){	             
				        
				    }
				});
		}
	}

	var tweetLoginJs = {
		// Tweet 로그인 관련 스크립트
		loginCheck : function() {
	
			var user_id = document.getElementById('user_id').value;
			var user_password = document.getElementById('user_password').value;
	
			if(user_id.length < 1) {
	             alert('아이디를 입력하세요.');
	             document.getElementById('user_id').focus();
	             return;
			}
			
			if(user_password.length < 1) {
	             alert('패스워드를 입력하세요.');
	             document.getElementById('user_password').focus();
	             return;
			}
			
			document.location.href='/login.do?user_id=' + user_id + '&user_password=' + user_password;
		}

	}



var tweetFollowJs = { 
		createFollowMember : function(oppositeID) {
	
			$.ajax({
			    url: '/createFollowMember4Ajax.do?oppositeID='+oppositeID,
			    type: 'POST',
			    dataType: 'json',
			    timeout: 3000,
			    complete: function(res) {
					var jsonData = eval("(" + res.responseText + ")");
					if(jsonData.errorCode == "1") {
						alert("Follow Success");
					} else {
						alert('error : ' + jsonData.errorDesc);
					}
					var findUserID = document.getElementById("findUserID").value;
					document.location.href='/findUser.do?findUserID='+findUserID;
				}
		 	});
		},
		removeFollowMember : function(oppositeID) {
			
			$.ajax({
			    url: '/removeFollowMember4Ajax.do?oppositeID='+oppositeID,
			    type: 'POST',
			    dataType: 'json',
			    timeout: 3000,
			    complete: function(res) {
					var jsonData = eval("(" + res.responseText + ")");
					if(jsonData.errorCode == "1") {
						alert("Unfollow Success");
					} else {
						alert('error : ' + jsonData.errorDesc);
					}
					var findUserID = document.getElementById("findUserID").value;
					document.location.href='/findUser.do?findUserID='+findUserID;
				}
		 	});
		}
}


/*
* This is the function that actually highlights a text string by
* adding HTML tags before and after all occurrences of the search
* term. You can pass your own tags if you'd like, or if the
* highlightStartTag or highlightEndTag parameters are omitted or
* are empty strings then the default <font> tags will be used.
*/
function doHighlight(bodyText, searchTerm, highlightStartTag, highlightEndTag) 
{
 // the highlightStartTag and highlightEndTag parameters are optional
 if ((!highlightStartTag) || (!highlightEndTag)) {
   highlightStartTag = "<font style='color:blue; background-color:yellow;'>";
   highlightEndTag = "</font>";
 }
 
 // find all occurences of the search term in the given text,
 // and add some "highlight" tags to them (we're not using a
 // regular expression search, because we want to filter out
 // matches that occur within HTML tags and script blocks, so
 // we have to do a little extra validation)
 var newText = "";
 var i = -1;
 var lcSearchTerm = searchTerm.toLowerCase();
 var lcBodyText = bodyText.toLowerCase();
   
 while (bodyText.length > 0) {
   i = lcBodyText.indexOf(lcSearchTerm, i+1);
   if (i < 0) {
     newText += bodyText;
     bodyText = "";
   } else {
     // skip anything inside an HTML tag
     if (bodyText.lastIndexOf(">", i) >= bodyText.lastIndexOf("<", i)) {
       // skip anything inside a <script> block
       if (lcBodyText.lastIndexOf("/script>", i) >= lcBodyText.lastIndexOf("<script", i)) {
         newText += bodyText.substring(0, i) + highlightStartTag + bodyText.substr(i, searchTerm.length) + highlightEndTag;
         bodyText = bodyText.substr(i + searchTerm.length);
         lcBodyText = bodyText.toLowerCase();
         i = -1;
       }
     }
   }
 }
 
 return newText;
}


/*
* This is sort of a wrapper function to the doHighlight function.
* It takes the searchText that you pass, optionally splits it into
* separate words, and transforms the text on the current web page.
* Only the "searchText" parameter is required; all other parameters
* are optional and can be omitted.
*/
function highlightSearchTerms(searchText, treatAsPhrase, warnOnFailure, highlightStartTag, highlightEndTag)
{
 // if the treatAsPhrase parameter is true, then we should search for 
 // the entire phrase that was entered; otherwise, we will split the
 // search string so that each word is searched for and highlighted
 // individually
 if (treatAsPhrase) {
   searchArray = [searchText];
 } else {
   searchArray = searchText.split(" ");
 }
 
 if (!document.body || typeof(document.body.innerHTML) == "undefined") {
   if (warnOnFailure) {
     alert("Sorry, for some reason the text of this page is unavailable. Searching will not work.");
   }
   return false;
 }
 
 var bodyText = document.body.innerHTML;
 //var bodyText = document.getElementById("timeline").innerHTML;
 for (var i = 0; i < searchArray.length; i++) {
   bodyText = doHighlight(bodyText, searchArray[i], highlightStartTag, highlightEndTag);
 }
 
 document.body.innerHTML = bodyText;
 return true;
}

